<script lang="ts" setup>
import type { SchoolApi } from '#/api/edu/base/school';

import { computed, onMounted, onUnmounted, ref, watchEffect } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, Card } from 'ant-design-vue';

import { getSchool } from '#/api/edu/base/school';

// 导入详情子组件
import BaseDetail from './base-detail.vue';
import ContactDetail from './contact-detail.vue';
import EducationDetail from './education-detail.vue';
import ExternalDetail from './external-detail.vue';
import FeaturesDetail from './features-detail.vue';
import IntroductionDetail from './introduction-detail.vue';
import LocationDetail from './location-detail.vue';
import MembershipDetail from './membership-detail.vue';
import QualificationDetail from './qualification-detail.vue';
import StatusDetail from './status-detail.vue';

const schoolData = ref<SchoolApi.School>({} as SchoolApi.School);
// 当前激活的锚点
const activeAnchor = ref('base-info');
const desensitize = ref(true);
async function handleDesensitize() {
  desensitize.value = !desensitize.value;
  const data = await getSchool(schoolData.value.id, desensitize.value);
  schoolData.value = data;
}
// 处理锚点点击事件，避免页面刷新
const handleAnchorClick = (e: MouseEvent) => {
  e.preventDefault();
  const targetId = (e.currentTarget as HTMLElement).dataset.target;
  if (targetId) {
    activeAnchor.value = targetId;
    const element = document.getElementById(targetId);
    if (element) {
      // 添加平滑滚动效果
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }
};

// 处理滚动事件，更新活动锚点
const handleScroll = () => {
  const sections = document.querySelectorAll('.section');
  let currentSectionId = 'base-info';
  let minDistance = Infinity;

  sections.forEach((section) => {
    const rect = section.getBoundingClientRect();
    // 计算距离视口顶部的距离
    const distance = Math.abs(rect.top - 100); // 100 是 offsetTop

    if (distance < minDistance) {
      minDistance = distance;
      currentSectionId = section.id;
    }
  });

  activeAnchor.value = currentSectionId;
};

// 组件挂载时添加滚动监听
onMounted(() => {
  const contentArea = document.querySelector('.content-area');
  if (contentArea) {
    contentArea.addEventListener('scroll', handleScroll);
    // 初始检查当前位置
    handleScroll();
  }
});

// 组件卸载时移除滚动监听
onUnmounted(() => {
  const contentArea = document.querySelector('.content-area');
  if (contentArea) {
    contentArea.removeEventListener('scroll', handleScroll);
  }
});

// 当 schoolData 加载完成后，更新活动锚点
watchEffect(() => {
  if (schoolData.value.id) {
    setTimeout(() => {
      handleScroll();
    }, 100);
  }
});
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      schoolData.value = {} as SchoolApi.School;
      return;
    }
    // 加载数据
    let data =
      drawerApi.getData<SchoolApi.School>() ?? ({} as SchoolApi.School);
    if (data.id) {
      drawerApi.lock();
      try {
        data = await getSchool(data.id, desensitize.value);
      } finally {
        drawerApi.unlock();
      }
    }

    schoolData.value = data;
  },
});

// 学校标题
const schoolTitle = computed(() => {
  return (
    schoolData.value.schoolName || schoolData.value.shortName || '学校详情'
  );
});
</script>

<template>
  <Drawer
    :title="schoolTitle"
    class="w-[80%]"
    :show-cancel-button="false"
    :show-confirm-button="false"
  >
    <div v-if="schoolData.id" class="detail-container">
      <!-- 左侧锚点导航 -->
      <div class="anchor-sidebar">
        <div class="custom-anchor">
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'base-info' }]"
            data-target="base-info"
            @click="handleAnchorClick"
          >
            基本信息
          </div>
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'membership-info' }]"
            data-target="membership-info"
            @click="handleAnchorClick"
          >
            行政隶属关系
          </div>
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'contact-info' }]"
            data-target="contact-info"
            @click="handleAnchorClick"
          >
            负责人
          </div>
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'location-info' }]"
            data-target="location-info"
            @click="handleAnchorClick"
          >
            位置信息
          </div>
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'education-info' }]"
            data-target="education-info"
            @click="handleAnchorClick"
          >
            办学属性
          </div>
        </div>
        <div class="custom-anchor">
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'features-info' }]"
            data-target="features-info"
            @click="handleAnchorClick"
          >
            教学特色
          </div>
        </div>
        <div class="custom-anchor">
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'qualification-info' }]"
            data-target="qualification-info"
            @click="handleAnchorClick"
          >
            资质认证
          </div>
        </div>
        <div class="custom-anchor">
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'status-info' }]"
            data-target="status-info"
            @click="handleAnchorClick"
          >
            状态信息
          </div>
        </div>
        <!-- 学校简介 -->
        <div class="custom-anchor">
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'introduction-info' }]"
            data-target="introduction-info"
            @click="handleAnchorClick"
          >
            学校简介
          </div>
        </div>
        <div class="custom-anchor">
          <div
            class="anchor-link"
            :class="[{ active: activeAnchor === 'external-info' }]"
            data-target="external-info"
            @click="handleAnchorClick"
          >
            与其他系统关系
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 基本信息 -->
        <div id="base-info" class="section">
          <Card title="基本信息" class="mb-2">
            <BaseDetail :school="schoolData" />
          </Card>
        </div>

        <!-- 行政隶属关系 -->
        <div id="membership-info" class="section">
          <Card title="行政隶属关系" class="mb-2">
            <MembershipDetail :school="schoolData" />
          </Card>
        </div>

        <!-- 负责人 -->
        <div id="contact-info" class="section">
          <ContactDetail
            :school="schoolData"
            :desensitize="desensitize"
            :show-desensitize-button="true"
            @change-desensitize="handleDesensitize"
          />
        </div>

        <!-- 位置信息 -->
        <div id="location-info" class="section">
          <Card title="位置信息" class="mb-2">
            <LocationDetail :school="schoolData" />
          </Card>
        </div>

        <!-- 办学属性 -->
        <div id="education-info" class="section">
          <Card title="办学属性" class="mb-2">
            <EducationDetail :school="schoolData" />
          </Card>
        </div>

        <!-- 教学特色 -->
        <div id="features-info" class="section">
          <Card title="教学特色" class="mb-2">
            <FeaturesDetail :school="schoolData" />
          </Card>
        </div>

        <!-- 资质认证 -->
        <div id="qualification-info" class="section">
          <Card title="资质认证" class="mb-2">
            <template #extra>
              <Button
                type="primary"
                @click="handleDesensitize"
                :danger="desensitize"
              >
                <IconifyIcon
                  :icon="
                    desensitize
                      ? 'ant-design:eye-filled'
                      : 'ant-design:eye-invisible-filled'
                  "
                />
                {{ desensitize ? '关闭脱敏' : '启用脱敏' }}
              </Button>
            </template>
            <QualificationDetail :school="schoolData" />
          </Card>
        </div>

        <!-- 状态信息 -->
        <div id="status-info" class="section">
          <Card title="状态信息" class="mb-2">
            <StatusDetail :school="schoolData" />
          </Card>
        </div>
        <!-- 学校简介 -->
        <div id="introduction-info" class="section">
          <Card title="学校简介" class="mb-2">
            <IntroductionDetail :school="schoolData" />
          </Card>
        </div>

        <!-- 与其他系统关系 -->
        <div id="external-info" class="section">
          <ExternalDetail :school-id="schoolData.id" />
        </div>
      </div>
    </div>
  </Drawer>
</template>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .detail-container {
    flex-direction: column;
    height: auto;
  }

  .anchor-sidebar {
    width: 100%;
    height: auto;
    max-height: 200px;
    padding-right: 0;
    margin-bottom: 16px;
    border-right: none;
    border-bottom: 1px solid #f0f0f0;
  }

  .content-area {
    padding: 0;
  }

  .section {
    margin-bottom: 10px;
    scroll-margin-top: 100px;
  }

  .ant-card {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  .anchor-sidebar :deep(.ant-anchor-link-title) {
    padding: 3px 6px;
    font-size: 13px;
  }

  .ant-card-head-title {
    font-size: 14px;
  }
}

.detail-container {
  display: flex;
  gap: 24px;
  height: calc(100vh - 100px);
  padding: 16px 0;
  overflow: hidden;
}

/* 左侧锚点导航 */
.anchor-sidebar {
  flex-shrink: 0;
  width: 160px;
  padding-right: 16px;
  overflow-y: auto;
  border-right: 1px solid #f0f0f0;
}

/* 自定义锚点样式 */
.custom-anchor {
  padding: 0;
}

.anchor-link {
  display: inline-block;
  width: 100%;
  padding: 10px 8px;
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.anchor-link:hover {
  color: #1890ff;
  background-color: #f5f5f5;
}

.anchor-link.active {
  font-weight: 500;
  color: #1890ff;
  background-color: #e6f7ff;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  padding: 0 16px;
  overflow-y: auto;
}

.section {
  margin-bottom: 12px;
  scroll-margin-top: 120px;
}

/* 优化卡片样式 */
.ant-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 5%);
  transition: all 0.3s ease;
}

.ant-card:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
}

.ant-card-head {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.ant-card-head-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 滚动条样式 */
.content-area::-webkit-scrollbar,
.anchor-sidebar::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.content-area::-webkit-scrollbar-track,
.anchor-sidebar::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.content-area::-webkit-scrollbar-thumb,
.anchor-sidebar::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
  transition: background 0.3s ease;
}

.content-area::-webkit-scrollbar-thumb:hover,
.anchor-sidebar::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 主容器样式 */
</style>
